import router from "@/router";
import {useLoginUserStore} from "@/stores/UseLoginUserStore";
import {message} from "ant-design-vue";

// 是否首次获取登录用户
let firstGetLoginUser = true

router.beforeEach(async (to, from, next) => {
    const loginUserStore = useLoginUserStore()
    let loginUser = loginUserStore.loginUser
    // 页面刷新时等待后端返回用户信息后再校验权限
    if (firstGetLoginUser){
        await loginUserStore.getLoginUser()
        loginUser = loginUserStore.loginUser
        firstGetLoginUser = false
    }
    const toUrl = to.fullPath
    // 自定义权限校验规则
    if (toUrl.startsWith("/admin")){
        if (!loginUser || loginUser.userRole !== 'admin'){
            message.error('没有权限')
            next(`/user/login?redirect=${to.fullPath}`)
            return
        }
    }
    next()
})
